import { useMutation } from "@tanstack/react-query";
import { fileAPI } from "@/api";
import { useTranslation } from "react-i18next";
import { AxiosError } from "axios";
import { toast } from "sonner";
import type { ErrorResponse } from "@/types/response";

export const useFileUpload = () => {
  const { t } = useTranslation();

  const mutation = useMutation({
    mutationFn: (file: File) => fileAPI.upload(file),
    onSuccess: (data) => {
      console.log("文件上传成功:", data);
      toast.success(t("Upload successful", { defaultValue: "上传成功" }), {
        description: t("File uploaded successfully", { defaultValue: "文件上传成功" }),
      });
      // 这里可以添加成功后的处理逻辑，比如更新用户头像等
    },
    onError: (error: AxiosError<ErrorResponse>) => {
      console.error("文件上传失败:", error);
      const errorMessage = error?.response?.data?.message || t("Upload failed", { defaultValue: "上传失败" });
      console.error("上传错误:", errorMessage);
      toast.error(t("Upload failed", { defaultValue: "上传失败" }), {
        description: errorMessage,
      });
    },
  });

  return {
    uploadFile: mutation.mutate,
    uploadFileAsync: mutation.mutateAsync,
    isUploading: mutation.isPending,
    isError: mutation.isError,
    error: mutation.error,
    isSuccess: mutation.isSuccess,
    data: mutation.data,
  };
};
